package com.cryann.mqttserver.mqttProcess;

import com.cryann.mqttserver.service.Impl.MqttSubjectImpl;
import com.cryann.mqttserver.service.MqttAccessor;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author cRyann
 * @date 2018/12/19 0019 10:26
 * @description:
 */
@Component
@Slf4j
@ProcessType(MqttMessageType.UNSUBSCRIBE)
public class UnSubScribe implements BasicProcess<MqttUnsubscribeMessage> {

    @Autowired
    MqttSubjectImpl mqttSubject;

    @Autowired
    MqttAccessor mqttAccessor;

    @Override
    public void process(Channel ctx, MqttUnsubscribeMessage msg) {
        mqttSubject.delSubject(ctx, msg);
        MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.UNSUBACK, false, msg.fixedHeader().qosLevel(), false, 0);
//        [MQTT-2.3.1-7] SUBACK和UNSUBACK必须包含在对应的SUBSCRIBE和UNSUBSCRIBE报文中使用的报文标识符。
        MqttMessageIdVariableHeader variableHeader = MqttMessageIdVariableHeader.from(msg.variableHeader().messageId());
        MqttUnsubAckMessage unsubAckMessage = new MqttUnsubAckMessage(fixedHeader, variableHeader);
        ctx.writeAndFlush(unsubAckMessage);
        mqttAccessor.unSubTopic(mqttAccessor.getAccessor(ctx), msg.payload().topics());
    }
}
